#include "Socket.hpp"
#include <memory>
#include "Comm.hpp"
#include <iostream>
#include "Log.hpp"
#include "Protocol.hpp"
#include <ctime>
#include "Calculate.hpp"

void Usage(const std::string &proc)
{
    std::cout << "格式：" << proc << " serverport serverip" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[1]);
        return usage_err;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    std::unique_ptr<TcpSocket> sock = std::make_unique<TcpSocket>();
    sock->CreateConnectSocket(serverip, serverport);
    // std::cout << sock->CreateConnectSocket(serverip, serverport) << std::endl;

    std::unique_ptr<Factory> factory = std::make_unique<Factory>();

    srand(time(nullptr));

    while (true)
    {
        int x = rand() % 100;
        usleep(100);
        int y = rand() % 100;
        usleep(100);
        char oper = opers[rand() % 5];
        std::shared_ptr<Request> req = factory->BulidRequest(x, y, oper);
        std::string req_message = req->Serialize();
        // std::cout << "req_message" << req_message << std::endl;

        std::string req_package = EnCode(req_message);
        // std::cout << "req_package" << req_package << std::endl;
        // for (int i = 0; i < req_package.size(); i++)
        //     std::cout << i << ": " << req_package[i] << std::endl;   //发送的没问题
        sock->Send(req_package);

        std::string resp_package = sock->Recv();
        // std::cout << "resp_package" << resp_package << std::endl;

        std::string resp_message = DeCode(resp_package);
        // std::cout << "resp_message" << resp_message << std::endl;

        std::shared_ptr<Response> resp = factory->BulidResponse();
        resp->DeSerialize(resp_message);
        std::cout << req_message << " = " << resp->Serialize() << std::endl;
        std::cout << "-------" << std::endl;
        sleep(1);
    }
    return 0;
}